package com.jh.user.service;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.*;
import com.google.common.collect.ImmutableList;
import com.jh.user.business.*;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.PayType;
import com.jh.user.util.CommonsUtil;
import com.jh.user.util.Util;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.StringUtils.trimToEmpty;


@Controller
public class UserLoginRegisterService {

    private final Logger LOG = LoggerFactory.getLogger(getClass());

    private final ShopRegisterBussiness shopRegisterBussiness;
    private final UserBalanceBusiness userBalBusiness;
    private final BrandManageBusiness brandMangeBusiness;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final BrandManageBusiness brandManageBusiness;
    private final UserShopsBusiness userShopsBusiness;
    private final UserBankInfoBusiness userBankInfoBusiness;
    private final ThirdLeveDistributionBusiness thirdLevelBusiness;
    private final UserRoleResourceBusiness userRoleResourceBusiness;
    private final Util util;
    private final RestTemplate restTemplate;
    private final RiskService riskService;

    @Autowired
    public UserLoginRegisterService(ShopRegisterBussiness shopRegisterBussiness,
                                    UserBalanceBusiness userBalBusiness,
                                    BrandManageBusiness brandMangeBusiness,
                                    UserLoginRegisterBusiness userLoginRegisterBusiness,
                                    BrandManageBusiness brandManageBusiness,
                                    UserShopsBusiness userShopsBusiness,
                                    UserBankInfoBusiness userBankInfoBusiness,
                                    ThirdLeveDistributionBusiness thirdLevelBusiness,
                                    UserRoleResourceBusiness userRoleResourceBusiness,
                                    Util util, RestTemplate restTemplate, RiskService riskService) {
        this.shopRegisterBussiness = shopRegisterBussiness;
        this.userBalBusiness = userBalBusiness;
        this.brandMangeBusiness = brandMangeBusiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.brandManageBusiness = brandManageBusiness;
        this.userShopsBusiness = userShopsBusiness;
        this.userBankInfoBusiness = userBankInfoBusiness;
        this.thirdLevelBusiness = thirdLevelBusiness;
        this.userRoleResourceBusiness = userRoleResourceBusiness;
        this.util = util;
        this.restTemplate = restTemplate;
        this.riskService = riskService;
    }

    @Autowired
    private ChannelRateBusiness  channelRateBusiness;

    /**
     * 外放用户临时开户
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/outchannel/new")
    public @ResponseBody
    Object registerUser(HttpServletRequest request, @RequestParam(value = "phone", required = false) String phone,
                        @RequestParam(value = "pre_phone", required = false) String prephone, @RequestParam(value = "brand_id", required = false, defaultValue = "-1") long brandid) {

        Map<String, Object> map = new HashMap<>();
        if (brandid == -1) {
            Brand brand = brandManageBusiness.findBrandById(brandid);
        } else {

        }
        User user = new User();
        user.setId(Long.parseLong(RandomUtils.generateNumString(9)));
        user.setCreateTime(new Date());
        // user.setOpenid(openid);
        user.setPassword(Md5Util.getMD5("123456"));
        user.setPhone(phone.trim());

        user.setGrade("0");
        user.setPaypass(Md5Util.getMD5("123456"));
        // user.setUnionid(unionid);
        user.setValidStatus(0);
        // user.setInviteCode(invitecode);
        user.setBrandId(brandid);
        user = userLoginRegisterBusiness.createOutNewUser(user);
        String userToken = TokenUtil.createToken(user.getId(), brandid, phone);
        user.setUserToken(userToken);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }


    /**
     * 根据用户的手机号码和贴牌返回用户的基本信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/1.0/user/query/phonebrand")
    public @ResponseBody
    Object queryUserInfoByPhoneBrandId(@RequestParam(value = "phone") String phone, @RequestParam(value = "brandid") String brandid) {
        User user = userLoginRegisterBusiness.queryUserByPhoneBrandid(phone, Long.parseLong(brandid));
        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 代理商开户接口
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/openaccount")
    public @ResponseBody
    Object openAccount(
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "fullname", required = false) String fullname,
            @RequestParam(value = "origcode", required = false) String origcode,
            @RequestParam(value = "signcode", required = false) String signcode,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "zipcode", required = false) String zipcode,
            @RequestParam(value = "contact_name", required = false) String contactname,
            @RequestParam(value = "grade", required = false) String grade,
            @RequestParam(value = "inviteCode", required = false) String inviteCode,
            @RequestParam(value = "pre_phone", required = false) String preUserPhone,
            @RequestParam(value = "brand_id", defaultValue = "1", required = false) long brandid,
            @RequestParam(value = "brand_name", defaultValue = "节付宝", required = false) String brandname) {

        Map<String, Object> map = new HashMap<>();
        User user;
        Brand brand = null;
        if (brandid == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandMangeBusiness.findBrandById(brandid);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        if (user != null && user.getId() != 0) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_HAS_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户已经注册");
            return map;

        } else {
            user = new User();
        }


        if (brand == null) {
            brand = brandMangeBusiness.findBrandById(brandid);
        }
        /*
         User preuser = null;
         if (prephone != null && !prephone.equalsIgnoreCase("")) {
         if (brandid == -1) {
         preuser = userLoginRegisterBusiness.queryUserByPhone(prephone);
         } else {

         if ("6".equals(brand.getBrandType())) {
         preuser = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(prephone, brandid);
         } else {
         preuser = userLoginRegisterBusiness.queryUserByPhone(prephone);
         }
         }


         if (preuser == null) {
         map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
         map.put(CommonConstants.RESP_MESSAGE, "上级用户不存在");
         return map;
         }
         }*/

        user.setId(Long.parseLong(RandomUtils.generateNumString(9)));
        user.setCreateTime(new Date());
        // user.setOpenid(openid);
        user.setPassword(Md5Util.getMD5("123456"));
        user.setPhone(phone.trim());
        user.setFullname(fullname);
        user.setOrigcode(origcode);
        user.setSigncode(signcode);
        user.setAddress(address);
        user.setZipcode(zipcode);
        user.setGrade(grade);
        user.setInviteCode(inviteCode);
        user.setPreUserPhone(preUserPhone);
        user.setContactname(contactname);
        user.setPaypass(Md5Util.getMD5("123456"));
        // user.setUnionid(unionid);
        user.setValidStatus(0);
        // user.setInviteCode(invitecode);
        user.setBrandId(brandid);
        user.setBrandname(brandname);

        setEmailAndAddress(user);

        /*
         if (preuser != null) {
         user.setPreUserId(preuser.getId());
         user.setPreUserPhone(prephone);
         }*/

        user = userLoginRegisterBusiness.createNewUser(user);
        String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
        user.setUserToken(userToken);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 获取验证码场景类型
     */
    public int getSMSRecordType(String phone) {
        URI uri2 = util.getServiceUrl("notice", "error url request!");
        String url2 = uri2.toString() + "/v1.0/notice/sms/vericodetype?phone=" + phone;
        String resultStr2 = restTemplate.getForObject(url2, String.class);
        JSONObject jsonObject2 = JSONObject.fromObject(resultStr2);                //已修改		付环宇2018.07.31
        return jsonObject2.getInt("result");
    }

    /**
     * 提取出注册过程 付环宇2018.08.15
     */
    private Map<String, Object> registerhelp(
            Map<String, Object> map, long uid, int type, String preUserphone, long brandid,
            Brand brand, String phone, String openid, String password, String paypass,
            String unionid, String brandname, String province, String city, String county) {
        /* 判断手机号码是否存在，如果已经存在， 那么不能继续 注册 */
        if (phone != null && !phone.equalsIgnoreCase("")) {
            User user;
            if (brandid == -1) {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            } else {
                if ("6".equals(brand.getBrandType())) {
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
                } else {
                    user = userLoginRegisterBusiness.queryUserByPhone(phone);
                }
            }

            if (user != null && user.getId() != 0) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_HAS_REGISTER);
                map.put(CommonConstants.RESP_MESSAGE, "用户已经注册");
                return map;
            }

        }
        User user = new User();
        User preuser = new User();
        if (StringUtils.isNotBlank(preUserphone)) {
            preuser = userLoginRegisterBusiness.queryUserByPhone(preUserphone);
            if (preuser == null) return CommonsUtil.returnError("推荐人号码不存在");
        }
        user.setId(uid);
        user.setCreateTime(new Date());
        user.setOpenid(openid);
        user.setPassword(Md5Util.getMD5(password));
        user.setPhone(phone);
        user.setPaypass(Md5Util.getMD5(paypass));
        user.setUnionid(unionid);
        user.setValidStatus(0);

        user.setPreUserId(preuser.getId());
        user.setPreUserPhone(preUserphone);
        user.setBrandId(brandid);
        user.setBrandname(brandname);
        user.setProvince(province);
        user.setCity(city);
        user.setCounty(county);

        setEmailAndAddress(user);

        user = userLoginRegisterBusiness.createNewUser(user);
        String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
        user.setUserToken(userToken);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 生成Email和address
     * @param user
     */
    private void setEmailAndAddress(User user) {
        /* 随机生成邮箱地址 */
        StringBuilder str = new StringBuilder();
        str.append((char) (Math.random () * 26 + 'A'));
        str.append((char) (Math.random () * 26 + 'a'));
        str.append((char) (Math.random () * 26 + 'a'));

        Random rand = new Random();
        int randNum = rand.nextInt(1000) + 9999999;
        if (randNum % 3 == 0) {
            user.setEmail(str.append(randNum) + "@163.com");
        } else if (randNum % 5 == 0) {
            user.setEmail(str.append(randNum) + "@qq.com");
        } else if (randNum % 7 == 0) {
            user.setEmail(str.append(randNum) + "@126.com");
        } else {
            user.setEmail(str.append(randNum) + "@outlook.com");
        }
        /* 默认地址 */
        user.setAddress("上海市浦东新区");
    }

    /**
     * 注册接口 用户注册 type=5/代理商注册 type=7
     **/
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/register")
    public @ResponseBody
    Object registerUser(HttpServletRequest request,
                        @RequestParam(value = "phone", required = false) String phone,
                        @RequestParam(value = "vericode", required = false) String vericode,
                        @RequestParam(value = "paypass", required = false) String paypass,
                        @RequestParam(value = "password") String password,
                        @RequestParam(value = "openid", required = false) String openid,
                        @RequestParam(value = "unionid", required = false) String unionid,
                        @RequestParam(value = "invitecode", required = false) String preUserPhone,  //推荐人手机号即上级用户手机号
                        @RequestParam(value = "brandId", defaultValue = "-1", required = false) long brandid,
                        @RequestParam(value = "brand_name", defaultValue = "开店管家", required = false) String brandname,
                        @RequestParam(value = "province", required = false) String province,
                        @RequestParam(value = "city", required = false) String city,
                        @RequestParam(value = "county", required = false) String county) {
        Map<String, Object> map = new HashMap<>();
        Brand brand = brandManageBusiness.findBrandById(brandid);

        if (brand != null) {
            brandname = brand.getName();
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
            map.put(CommonConstants.RESP_MESSAGE, "贴牌错误");      //“上级用户不存在”修改为“贴牌错误”
            return map;
        }

        /* 如果短信验证码不为空， 那么需要 */
        RestTemplate restTemplate = new RestTemplate();
        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(phone);        //获取验证码场景类型
        /*将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) && codetype != 5) {   //codetype=5 OEM后台注册后角色也为普通用户
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }
        //codetype:5用户注册,7代理商注册,OEM注册成功后也为普通用户角色
        if (StringUtils.isNotBlank(code) && code.equalsIgnoreCase(vericode) && (codetype == 5 || codetype == 7)) {
            long uid = Long.parseLong(RandomUtils.generateNumString(9));
            map = registerhelp(map, uid, codetype, preUserPhone, brandid, brand, phone, openid, password, paypass, unionid, brandname, province, city, county);     //调用注册
//            if ("成功".equals(map.get(CommonConstants.RESP_MESSAGE))) {
//                UserRole userRole = new UserRole();
//                userRole.setUserId(uid);
//                userRole.setRoleId(5);      //roleid=5 普通用户
//                userRole.setStatus("0");
//                userRole.setCreateTime(new Date());
//                UserRole userRole1 = userRoleResourceBusiness.adduserRole(userRole);
//                if (userRole1.getRoleId() == 5) {
//                    return map;
//                } else {
//                    return CommonsUtil.returnError("用户角色添加失败");
//                }
//            }
            return map;
        } /*else if (code.equalsIgnoreCase(vericode) && codetype == 7) {
            long uid = Long.parseLong(RandomUtils.generateNumString(9));
            map = registerhelp(map, uid, codetype, preUserPhone, brandid, brand, phone, openid, password, paypass, unionid, brandname, province, city, county);       //调用注册
            if ("成功".equals(map.get(CommonConstants.RESP_MESSAGE))) {
                UserRole userRole = new UserRole();
                userRole.setUserId(uid);
                userRole.setRoleId(3);      //roleid=3 代理商
                userRole.setStatus("0");
                userRole.setCreateTime(new Date());
                UserRole userRole1 = userRoleResourceBusiness.adduserRole(userRole);
                if (userRole1.getRoleId() == 3) {
                    return map;
                } else {
                    return CommonsUtil.returnError("代理商角色添加失败");
                }
            }
            return map;
        } else */
        {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }
    }

    /**
     * 上级代注接口
     **/
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/pre/register")
    public @ResponseBody
    Object preRegisterUser(
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "openid", required = false) String openid,
            @RequestParam(value = "unionid", required = false) String unionid,
            @RequestParam(value = "invitecode", required = false) String invitecode,
            @RequestParam(value = "brand_id", defaultValue = "1", required = false) long brandid,
            @RequestParam(value = "brand_name", defaultValue = "节付宝", required = false) String brandname) {
        try {
            String paypass = "123456";
            String password = "123456";

            Map<String, Object> map = new HashMap<>();
            Brand brand = brandManageBusiness.findBrandById(brandid);

            /* 判断手机号码是否存在，如果已经存在， 那么不能继续 注册 */
            if (phone != null && !phone.equalsIgnoreCase("")) {
                User user;
                if ("6".equals(brand.getBrandType())) {
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
                } else {
                    user = userLoginRegisterBusiness.queryUserByPhone(phone);
                }
                if (user != null && user.getId() != 0) {

                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_HAS_REGISTER);
                    map.put(CommonConstants.RESP_MESSAGE, "用户已经注册");
                    return map;
                }

            }

            User user = new User();
            user.setId(Long.parseLong(RandomUtils.generateNumString(9)));
            user.setCreateTime(new Date());
            user.setOpenid(openid);
            user.setPassword(Md5Util.getMD5(password));
            user.setPhone(phone);
            user.setPaypass(Md5Util.getMD5(paypass));
            user.setUnionid(unionid);
            user.setValidStatus(0);
            user.setInviteCode(invitecode);
            user.setBrandId(brandid);
            user.setBrandname(brandname);

            setEmailAndAddress(user);

            /*
             if (preuser != null) {
             user.setPreUserPhone(preuser.getPhone());
             user.setPreUserId(preuser.getId());
             }*/
            user = userLoginRegisterBusiness.createNewUser(user);
            String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
            user.setUserToken(userToken);

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESULT, user);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            return map;
        } catch (Exception e) {
            return CommonsUtil.returnError("注册失败！");
        }
    }

    /**
     * 更换用户账户手机号    type=6
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/phone/update/{token}")
    public @ResponseBody
    Object updatePhone(
            @PathVariable("token") String token,
            // 更换手机收到的验证码
            @RequestParam(value = "vericode", required = false) String vericode,
            // 更换手机号
            @RequestParam(value = "phone", required = false) String phone,
            // 当前登录密码
            @RequestParam(value = "password", required = false) String password) {

        Map<String, Object> map = new HashMap<>();
        long userId;
        long brandId;
        try {
            userId = TokenUtil.getUserId(token);
            brandId = TokenUtil.getBrandid(token);
        } catch (Exception e) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN, "token无效");
        }

        try {
            /* 如果短信验证码不为空， 那么需要 */
            URI uri = util.getServiceUrl("notice", "error url request!");
            String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
            String resultStr = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.fromObject(resultStr);
            String code = jsonObject.getString("result");
            int codetype = getSMSRecordType(phone);        //获取验证码场景类型
            /* 将错误情况区分开 付环宇2018.08.14*/
            if (StringUtils.isBlank(vericode)) {
                return CommonsUtil.returnError(CommonConstants.ERROR_VERI_CODE, "验证码不能为空！");
            }
            if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 6) {
                return CommonsUtil.returnError(CommonConstants.ERROR_VERI_CODE, "验证码错误！");
            }
            Brand brand = brandManageBusiness.findBrandById(brandId);
            /* 判断手机号码是否存在，如果已经存在， 那么不能继续 注册 */
            if (StringUtils.isNotBlank(phone)) {
                User user;
                if ("6".equals(brand.getBrandType())) {
                    user = userLoginRegisterBusiness.queryUserByPhone(phone);
                } else {
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
                }
                if (user != null && user.getId() != 0) {
                    return CommonsUtil.returnError(CommonConstants.ERROR_USER_HAS_REGISTER, "用户已经注册！");
                }

            }

            User user = userLoginRegisterBusiness.queryUserById(userId);

            if (!user.getPassword().equals(Md5Util.getMD5(password))) {
                return CommonsUtil.returnError(CommonConstants.ERROR_PAY_PASS, "支付密码错误！");
            }

            user.setPhone(phone.trim());
            userLoginRegisterBusiness.saveUser(user);
            return CommonsUtil.returnSuccess("");
        } catch (Exception e) {
            LOG.error("UserLoginRegisterService.updatePhone,更换用户手机userId=======" + userId + ", 异常========" + e);
            return CommonsUtil.returnError("更换用户手机失败！");
        }

    }

    /**
     * 用户密码登陆
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/login")
    public @ResponseBody
    Object login(@RequestParam(value = "phone") String phone,
                 @RequestParam(value = "brand_id", defaultValue = "1", required = false) long brandid,
                 @RequestParam(value = "password") String password,
                 @RequestParam(value = "deviceId") String deviceId,
                 @RequestParam(value = "source") String source) {

        // 简化微服务间的相互调用，modified at 2018/08/26 by Fuchun
        Map<String, Object> rs = riskService.isInBlacklist(phone, "0");
        if (!CommonConstants.SUCCESS.equals(rs.get("resp_code"))) {
            return CommonsUtil.returnError(CommonConstants.ERROR_USER_BLACK, "用户在黑名单中");
        }

        String pass = Md5Util.getMD5(password);
        User user = userLoginRegisterBusiness.isValidUser(phone, pass, brandid, deviceId,source);

        if (user != null && user.getId() > 0) {
            String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
            user.setUserToken(userToken);
            return CommonsUtil.returnSuccess(user);
        } else {
            return CommonsUtil.returnError(CommonConstants.ERROR_PASS_ERROR, "用户不存在或用户密码错误");
        }
    }

    /**
     * 更新用户的openid
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/update/openid")
    public @ResponseBody
    Object updateOpenid(@RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                        @RequestParam("phone") String phone,
                        @RequestParam(value = "openid") String openid) {
        long brandId;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        User user;
        Brand brand;
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandManageBusiness.findBrandById(brandId);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }
        user.setOpenid(openid);
        userLoginRegisterBusiness.saveUser(user);
        return CommonsUtil.returnSuccess("");
    }

    /**
     * 邀请码验证
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/verify/id/{token}")
    public @ResponseBody
    Object verifyuid(@PathVariable("token") String token, @RequestParam(value = "user_id") long userid) {

        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN, "token无效");
        }
        try {
            if (userId != userid) {
                return CommonsUtil.returnError(CommonConstants.FALIED, "校验失败");
            }
            User user = userLoginRegisterBusiness.queryUserById(userId);
            user.setVerifyStatus("1");
            return CommonsUtil.returnSuccess(userLoginRegisterBusiness.saveUser(user));
        } catch (Exception e) {
            LOG.error("UserLoginRegisterService.verifyuid, 邀请码验证，userId=======" + userId + ", 异常=======" + e);
            return CommonsUtil.returnError("邀请码验证失败！");
        }

    }


    /**
     * 用户密码登陆(后台)
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/backstage/login")
    public @ResponseBody
    Object BackstageLogin(HttpServletRequest request,
                          @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                          @RequestParam(value = "phone") String phone,
                          @RequestParam(value = "password") String password,
                          @RequestParam(value = "urlType") int urlType  //1.总后台登录，2.OEM登录
    ) {

        Map<String, Object> map = new HashMap<>();

        // 简化微服务间的相互调用，modified at 2018/08/26 by Fuchun
        Map<String, Object> rs = riskService.isInBlacklist(phone, "0");
        if (!CommonConstants.SUCCESS.equals(rs.get("resp_code"))) {
            return CommonsUtil.returnError(CommonConstants.ERROR_USER_BLACK, "用户在黑名单中");
        }

        String pass = Md5Util.getMD5(password);
        long brandId;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        User user;
        //Brand brand;
        if (brandId == -1) {
            //return CommonsUtil.returnError("贴牌错误");
            /*通过手机号和密码获取用户对象*/
            user = userLoginRegisterBusiness.queryUserByPhoneAndPassword(phone, pass);
        } else {
            //brand = brandManageBusiness.findBrandById(brandId);
            //brandType : 0自主品牌 1其他品牌
            /*if ("0".equals(brand.getBrandType())) {*/
            user = userLoginRegisterBusiness.isValidUser(phone, pass, brandId,"","");
            /*} else {
                user = userLoginRegisterBusiness.isValidUser(phone, pass);
            }*/
        }

        if (urlType == 1) {
            if (user != null && user.getId() > 0) {
                /* 判断权限 付环宇2018.08.17 */
                UserRole userRole = userRoleResourceBusiness.findByUserIdAndStatus(user.getId(), "0");
                if (userRole == null) {
                    return CommonsUtil.returnError("该用户无任何角色");
                }
                long roleid = userRole.getRoleId();
                /*for(UserRole ur : userRoleList){
                    if(ur.getRoleId() == 4) roleid = ur.getRoleId();
                }
                for(UserRole ur : userRoleList){
                    if(ur.getRoleId() == 1) roleid = ur.getRoleId();
                }*/
                // 1:系统管理 4: 审核员；
                if (roleid != 1 && roleid != 4) {
                    return CommonsUtil.returnError(CommonConstants.ERROR_USERROLE_ERROR, "登录失败，权限不足");
                }
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
                user.setUserToken(userToken);
                map.put(CommonConstants.RESULT, user);
                map.put(CommonConstants.USER_ROLEID, roleid);
                map.put(CommonConstants.RESP_MESSAGE, "登录成功,欢迎您：" + userRoleResourceBusiness.findById(roleid).getRolename());

                return map;
            } else {
                return CommonsUtil.returnError("用户密码错误");
            }
        } else if (urlType == 2) {
            if (user != null && user.getId() > 0) {
                /* 判断权限 付环宇2018.08.17 */
                UserRole userRole = userRoleResourceBusiness.findByUserIdAndStatus(user.getId(), "0");
                if (userRole == null) {
                    return CommonsUtil.returnError("该用户无任何角色");
                }
                long roleid = userRole.getRoleId();
                //
                /*for(UserRole ur : userRoleList){
                    if(ur.getRoleId() == 3) roleid = ur.getRoleId();
                }
                for(UserRole ur : userRoleList){
                    if(ur.getRoleId() == 2) roleid = ur.getRoleId();
                }
                for(UserRole ur : userRoleList){
                    if(ur.getRoleId() == 1) roleid = ur.getRoleId();
                }*/
                // roleid: 1:系统管理 2:贴牌商 3: 代理商
//                if (roleid != 1 && roleid != 2) {
//                    return CommonsUtil.returnError(CommonConstants.ERROR_USERROLE_ERROR, "登录失败，权限不足");
//                }
                // roleid: 1:系统管理 2:贴牌商 3: 代理商 6: 台卡代理
                if (roleid != 1 && roleid != 6) {
                    return CommonsUtil.returnError(CommonConstants.ERROR_USERROLE_ERROR, "登录失败，权限不足");
                }

                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
                user.setUserToken(userToken);
                map.put(CommonConstants.RESULT, user);
                map.put(CommonConstants.USER_ROLEID, roleid);
                map.put(CommonConstants.RESP_MESSAGE, "登录成功,欢迎您：" + userRoleResourceBusiness.findById(roleid).getRolename());
                return map;
            } else {
                return CommonsUtil.returnError("用户密码错误");
            }
        } else {//urlType不等于1.总后台登录，和2.OEM登录
            return CommonsUtil.returnError("urlType错误");
        }
    }

    /**
     * 用户和短信验证码登录   type=1
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/smslogin")
    public @ResponseBody
    Object smslogin(
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
            @RequestParam(value = "vericode") String vericode) {
        Map<String, Object> map = new HashMap<>(3);

        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(phone);        //获取验证码场景类型
        /* 将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 1) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }
        long brandId;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        User user;
        Brand brand;
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandManageBusiness.findBrandById(brandId);
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
        }
        if (user == null) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;

        }
        String userToken = TokenUtil.createToken(user.getId(), user.getBrandId(), user.getPhone());
        user.setUserToken(userToken);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 验证用户的支付密码
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/paypass/auth/{token}")
    public @ResponseBody
    Object veriPaypass(
            @PathVariable("token") String token,
            @RequestParam(value = "paypass") String paypass) {
        Map<String, Object> map = new HashMap<>(2);

        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }

        User user = userLoginRegisterBusiness.isPaypassValid(userId, Md5Util.getMD5(paypass));

        if (user != null && user.getId() > 0) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");

        } else {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PAY_PASS);
            map.put(CommonConstants.RESP_MESSAGE, "支付密码错误");

        }

        return map;
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/paypass/auth/userid")
    public @ResponseBody
    Object veriUserPaypass(
            @RequestParam(value = "userId") String suserId,
            @RequestParam(value = "paypass") String paypass
    ) {
        Map<String, Object> map = new HashMap<>(2);
        long userId;
        try {
            userId = Long.valueOf(suserId);
            if ("".equals(suserId) || "".equals(paypass)) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "亲.输入参数有误,请检查后重试!");
                return map;
            }
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.输入参数有误,请检查后重试!");
            return map;
        }

        User user = userLoginRegisterBusiness.isPaypassValid(userId, Md5Util.getMD5(paypass));

        if (user != null && user.getId() > 0) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PAY_PASS);
            map.put(CommonConstants.RESP_MESSAGE, "支付密码错误");
        }
        return map;
    }


    /**
     * 更新用户的支付密码    type=4
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/paypass/update/{token}")
    public @ResponseBody
    Object updatePaypass(
            @PathVariable("token") String token,
            @RequestParam(value = "vericode", required = false) String vericode,
            @RequestParam(value = "paypass") String paypass) {

        Map<String, Object> map = new HashMap<>();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;

        }

        User user = userLoginRegisterBusiness.queryUserById(userId);

        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + user.getPhone();
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(user.getPhone());        //获取验证码场景类型
        /* 将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 4) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }

        user.setPaypass(Md5Util.getMD5(paypass));
        userLoginRegisterBusiness.saveUser(user);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;
    }

    /**
     * 分页查询下级用户以User返回
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/afterFind/{token}")
    public @ResponseBody
    Object findPage(
            @PathVariable("token") String token,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty,

            @RequestParam(value = "realnameStatus", defaultValue = "", required = false) String realNameStatus,
            @RequestParam(value = "usershopStatus", defaultValue = "", required = false) String shopsStatus,
            @RequestParam(value = "roleId", defaultValue = "3", required = false) int roleId,     //roleId:1系统管理2贴牌商3代理商4审核员5普通用户
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,

            @RequestParam(value = "fullname", defaultValue = "", required = false) String fullname,
            @RequestParam(value = "startTime", defaultValue = "1990/01/01", required = false) Date startTime) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception ignored) {
            return CommonsUtil.returnError(CommonConstants.ERROR_TOKEN, "token无效");
        }
        User myuser = userLoginRegisterBusiness.findUserById(userId);
        if (roleId == 1) {
            return CommonsUtil.returnSuccess(userLoginRegisterBusiness.findUsersBywhere(-1, null, phone, fullname, realNameStatus, shopsStatus, startTime, pageable));
        } else if (roleId == 2) {
            return CommonsUtil.returnSuccess(userLoginRegisterBusiness.findUsersBywhere(myuser.getBrandId(), null, phone, fullname, realNameStatus, shopsStatus, startTime, pageable));
        } else {
            return CommonsUtil.returnSuccess(userLoginRegisterBusiness.findUsersBywhere(-1, myuser.getPhone(), phone, fullname, realNameStatus, shopsStatus, startTime, pageable));
        }
    }


    /**
     * 获取用户的下级会员（前端调用以UserInfo返回）
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/afer/{token}")
    public @ResponseBody
    Object afterUserInfo(
            @PathVariable("token") String token,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty,

            @RequestParam(value = "realnameStatus", defaultValue = "", required = false) String realNameStatus,
            @RequestParam(value = "usershopStatus", defaultValue = "", required = false) String shopsStatus,
            @RequestParam(value = "roleId", defaultValue = "3", required = false) int roleId,     //roleId:1系统管理2贴牌商3代理商4审核员5普通用户
            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,

            @RequestParam(value = "fullname", defaultValue = "", required = false) String fullname,
            @RequestParam(value = "startTime", defaultValue = "1990/01/01", required = false) Date startTime
    ) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));
        int todayAfterCount;
        int yesterdayAfterCount = 0;
        Map<String, Object> map = new HashMap<>();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception ignored) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }
        User myuser = userLoginRegisterBusiness.findUserById(userId);
        List<User> users;

        if (roleId == 1) {
            users = userLoginRegisterBusiness.findUsersBywhere(-1, null, phone, fullname, realNameStatus, shopsStatus, startTime);
        } else if (roleId == 2) {
            users = userLoginRegisterBusiness.findUsersBywhere(myuser.getBrandId(), null, phone, fullname, realNameStatus, shopsStatus, startTime);
        } else {
            users = userLoginRegisterBusiness.findUsersBywhere(-1, myuser.getPhone(), phone, fullname, realNameStatus, shopsStatus, startTime);
        }

        Map<String, Object> object = new HashMap<>();
        int totalElememts = users.size();
        int totalpages = (totalElememts / size) + 1;
        object.put("number", page);
        object.put("page", page);
        if (page > totalpages) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESULT, null);
            map.put(CommonConstants.RESP_MESSAGE, "页面超出");
            return map;
        }
        object.put("numberOfElements", size);
        object.put("totalElememts", totalElememts);
        object.put("totalpages", totalpages);
        StringBuilder sb = new StringBuilder();
        for (User user : users) {
            sb.append(user.getId()).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
            String[] str1 = sb.toString().split(",");
            Long[] str2 = new Long[str1.length];
            for (int j = 0; j < str1.length; j++) {
                str2[j] = Long.valueOf(str1[j]);
            }
            users = userLoginRegisterBusiness.findInfoUsersPageable(str2, pageable);
        }
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        todayAfterCount = userLoginRegisterBusiness.queryUserAfterTodayCount(userId,
                DateUtil.getDateStringConvert("", date, "yyyy-MM-dd"));
        calendar.add(Calendar.DATE, -1);
        date = calendar.getTime();
        try {
            yesterdayAfterCount = userLoginRegisterBusiness.queryUserAfterYesterdayCount(
                    userId, DateUtil.getDateStringConvert("", date, "yyyy-MM-dd"));
        } catch (Exception e) {
            LOG.error("Exception: {}", e.getLocalizedMessage() != null ? e.getLocalizedMessage() : e.getMessage());
        }

        object.put("content", getinfousers(users));
        map.put("todayAfterCount", todayAfterCount);
        map.put("yesterdayAfterCount", yesterdayAfterCount);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;

    }

    /**
     * 获取用户的下级会员
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/afer/userid")
    public @ResponseBody
    Object afterUserInfobyuid(
            @RequestParam("user_id") long userId,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        Map<String, Object> map = new HashMap<>();

        Page<User> userPage = userLoginRegisterBusiness.findByPreUserId(userId, pageable);

        Map<String, Object> object = new HashMap<>();
        object.put("number", userPage.getNumber());
        object.put("page", page);
        object.put("numberOfElements", size);
        object.put("totalElements", userPage.getTotalElements());
        object.put("totalPages", userPage.getTotalPages());

        object.put("content", getinfousers(userPage.getContent()));
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    private List<InfoUser> getinfousers(List<User> users) {
        if (users.size() == 0) return null;
        List<InfoUser> infousers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        JSONObject authObject;
        for (int i = 0; i < users.size(); i++) {
            sb.append(users.get(i).getId());
            if (i != users.size() - 1) {
                sb.append(",");
            }
        }
        JSONObject realNameJson = getRealNameJSONObjectByUserIds(sb.toString());
        JSONObject sumProfitRecoders = getSumProfitByUserIds(sb.toString());
        JSONObject sumType2Json = getSumPayTypeJSONObjectByUserIds(sb.toString(), "2");
        JSONObject sumType0Json = getSumPayTypeJSONObjectByUserIds(sb.toString(), "0");
        for (User user : users) {
            UserBankInfo ubi = userBankInfoBusiness.queryDefUserBankInfoByUserid(user.getId());
            UserAccount userAccount = userBalBusiness.queryUserAccountByUserid(user.getId());

            InfoUser infouser = new InfoUser();

            // 系统编号
            infouser.setUserid(user.getId());

            // 用户手机号
            infouser.setPhone(user.getPhone());

            infouser.setFullname(user.getFullname());
            // 用户性别
            infouser.setSex(user.getSex());
            if (ubi != null) {
                infouser.setBankName(ubi.getBankName());
                infouser.setCardNo(ubi.getCardNo());
                // 真是姓名
                infouser.setRealname(ubi.getUserName());
                // 身份证号
                infouser.setIdcard(ubi.getIdcard());
            } else {
                authObject = realNameJson.getJSONObject(user.getId() + "");

                if (authObject != null && !authObject.isNullObject()) {
                    String realName = authObject.getString("realname"),
                            idCard = authObject.getString("idcard");
                    infouser.setRealname(realName == null || realName.equals("null") ? null : realName);
                    // 身份证号
                    infouser.setIdcard(idCard == null || idCard.equals("null") ? null : idCard);
                } else {
                    infouser.setRealname(null);
                    infouser.setIdcard(null);
                }
            }
            // 实名状态
            infouser.setRealnameStatus(user.getRealnameStatus());

            // 省
            infouser.setProvince(user.getProvince());

            // 市
            infouser.setCity(user.getCity());

            // 区
            infouser.setCounty(user.getCounty());

            // 商铺状态
            infouser.setUsershopStatus(user.getShopsStatus());
            if (("1").equals(user.getShopsStatus())) {
                UserShops uShop = userShopsBusiness.findUserShopsByUid(user.getId());
                infouser.setUserShopName(uShop !=null ? uShop.getName() : "");
                infouser.setUserShopAddress(uShop !=null ? uShop.getAddress() : "");
                infouser.setUserShopName(trimToEmpty(uShop == null ? "" : uShop.getName()));
                infouser.setUserShopAddress(trimToEmpty(uShop == null ? "" : uShop.getAddress()));
            }
            infouser.setBrandId(user.getBrandId());
            infouser.setBrandName(trimToEmpty(user.getBrandname()));
            fillUserAccount(infouser, userAccount);

            String sumFieldName = String.valueOf(user.getId());
            infouser.setRechargeSum(resolveSum(sumType0Json, sumFieldName));
            infouser.setWithdrawSum(resolveSum(sumType2Json, sumFieldName));
            infouser.setRebateSum(resolveSum(sumProfitRecoders, sumFieldName));
            // 级别
            infouser.setGrade(user.getGrade());
            // 提款费
            BrandRate randRate = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), 1,user.getGrade(), PayType.WITHDRAW.getValue());
            if (randRate != null && randRate.getExtraFee() != null) {
                infouser.setWithdrawFee(randRate.getExtraFee().setScale(2, BigDecimal.ROUND_DOWN));
            } else {
                infouser.setWithdrawFee(new BigDecimal("2.00"));
            }
            // 注册时间
            infouser.setCreateTime(user.getCreateTime());
            infousers.add(infouser);
        }
        return infousers;

    }

    private void fillUserAccount(InfoUser infoUser, UserAccount account) {
        if (account == null) return;
        infoUser.setBalance(account.getBalance());
        infoUser.setFreezeBalance(account.getFreezeBalance());
        infoUser.setCoin(account.getCoin());
        infoUser.setRebateBalance(account.getRebateBalance());
        infoUser.setFreezerebateBalance(account.getFreezerebateBalance());
    }

    private BigDecimal resolveSum(JSONObject obj, String fieldName) {
        String fieldValue;
        try {
            fieldValue = obj.getString(fieldName);
            if ("null".equals(fieldValue) || fieldValue.isEmpty()) {
                fieldValue = "0";
            }
        } catch (Exception e1) {
            fieldValue = "0";
        }
        return new BigDecimal(fieldValue);
    }

    //优化后
    private JSONObject getRealNameJSONObjectByUserIds(String userIds) {
        URI uri = util.getServiceUrl("paymentchannel", "error url request!");
        String url = uri.toString() + "/v1.0/paymentchannel/realname/findby/userids";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("userIds", userIds);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        return jsonObject.getJSONObject(CommonConstants.RESULT);
    }

    private JSONObject getSumPayTypeJSONObjectByUserIds(String userIds, String type) {
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/byuserids";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("userIds", userIds);
        requestEntity.add("type", type);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        return jsonObject.getJSONObject(CommonConstants.RESULT);
    }

    private BigDecimal getSumPayType(long userid, String type) {

        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/payment/query/userid";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("user_id", userid + "");
        requestEntity.add("type", type);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String resultsum = jsonObject.getString("result");
        if (resultsum != null && !resultsum.equals("") && !resultsum.equalsIgnoreCase("null")) {
            return new BigDecimal(resultsum);
        } else {
            return new BigDecimal("0.00");
        }
    }

    //	优化后
    private JSONObject getSumProfitByUserIds(String acqUserIds) {
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/profit/query/byuserids";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("acqUserIds", acqUserIds);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        return jsonObject.getJSONObject(CommonConstants.RESULT);
    }


    private BigDecimal getSumProfit(long userid) {
        URI uri = util.getServiceUrl("transactionclear", "error url request!");
        String url = uri.toString() + "/v1.0/transactionclear/profit/query/userid";
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
        requestEntity.add("acq_user_id", userid + "");
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String resultsum = jsonObject.getString("result");
        if (resultsum != null && !resultsum.equals("") && !resultsum.equalsIgnoreCase("null")) {
            return new BigDecimal(resultsum);
        } else {
            return new BigDecimal("0.00");
        }
    }

    /**
     * 获取用户的上级会员
     */
    @RequestMapping(method = RequestMethod.GET, value = "/v1.0/user/superior/userid")
    public @ResponseBody
    Object superiorUserInfo(
            @RequestParam("userid") long userid,
            @RequestParam(value = "superiornum", defaultValue = "3", required = false) long superiornum) {

        User user = userLoginRegisterBusiness.queryUserById(userid);
        if (user == null) return CommonsUtil.returnError("用户ID错误");
        Map<String, Object> map = new HashMap<String, Object>();
        if (user.getPreUserId() == 0) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
            map.put(CommonConstants.RESP_MESSAGE, "无上级会员");

            return map;
        }
        List<User> users = new ArrayList<User>();
        String phone = user.getPreUserPhone();
        for (int i = 0; i < superiornum; i++) {
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, user.getBrandId());

            if (user == null) {
                break;
            }
            if (user.getId() == 756091451) {
                break;
            }
            users.add(user);
            if (user.getPreUserPhone() == null) {
                break;
            }
            phone = user.getPreUserPhone();

        }

        List<AfterUser> afterusers = new ArrayList<>();
        for (User us : users) {

            AfterUser afterUser = new AfterUser();
            afterUser.setUserid(us.getId());
            afterUser.setGrade(us.getGrade());
            afterUser.setName(us.getNickName());
            afterUser.setPhone(us.getPhone());
            afterusers.add(afterUser);

        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, afterusers);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;

    }

    /**
     * 根据用户的手机号码返回用户的基本信息
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/phone")
    public @ResponseBody
    Object queryUserInfoByPhone(
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId
    ) {

        Map<String, Object> map = new HashMap<>(3);
        long brandId;
        User user;
        Brand brand;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandManageBusiness.findBrandById(brandId);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 根据用户的id查询用户的基本信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/id")
    public @ResponseBody
    Object queryUserInfoById(@RequestParam(value = "id") long id) {
        User user = userLoginRegisterBusiness.queryUserById(id);
        Map<String, Object> map = new HashMap<>(3);
        if (user != null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
        }

        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 根据用户的grade查询用户的基本信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/grade")
    public @ResponseBody
    Object queryUserInfoByGrade(
            /* 等级 */ @RequestParam(value = "grade", required = false) String grade,
            /* 贴牌号 */ @RequestParam(value = "brand_id", defaultValue = "0", required = false) long brandid) {
        List<User> users = userLoginRegisterBusiness.queryUserByGrade(brandid, grade);
        if (users == null) users = ImmutableList.of();
        String userIds = null;
        if (!users.isEmpty()) {
            userIds = users.stream()
                    .map(u -> String.valueOf(u.getId()))
                    .collect(Collectors.joining(","));
        }
        Map<String, Object> object = new HashMap<>(2);
        object.put("users", users);
        object.put("uids", userIds);
        Map<String, Object> map = new HashMap<>(3);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 根据用户的brandid查询用户的基本信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/brandid")
    public @ResponseBody
    Object queryUserByBrandId(HttpServletRequest request,
                              @RequestParam(value = "brand_id") long brandid) {
        List<User> users = new ArrayList<User>();
        users = userLoginRegisterBusiness.queryUserByBrandId(brandid);
        String uids = "";
        for (User user : users) {
            uids += user.getId() + ",";
        }
        Map<String, Object> object = new HashMap<String, Object>();
        object.put("users", users);
        object.put("uids", uids);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 根据用户的id修改等级
     */
    @SuppressWarnings("unused")
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/grade/update")
    public @ResponseBody
    Object updateUserInfoById(HttpServletRequest request, @RequestParam(value = "id") long id,
                              @RequestParam(value = "grade") String grade) {
        try {
            Map<String,Object> resMap = new HashMap<String,Object>();
            User user = userLoginRegisterBusiness.queryUserById(id);
            if (Integer.parseInt(grade) != 0) {
                ThirdLevelDistribution distribution = thirdLevelBusiness.getThirdLevelByBrandidandgrade(user.getBrandId(),
                        Integer.parseInt(grade));
                if (distribution != null) {
                    List<ThirdLevelRate> thirdLevelRates = thirdLevelBusiness.findAllThirdLevelRates(distribution.getId());
                    for (ThirdLevelRate thirdLevelRate : thirdLevelRates) {
                        /* 自动添加等级费率 */
                        try {
                            Map<String, Object> stringObjectMap = addChannelGradeRate(resMap, user, thirdLevelRate);
                        } catch (Exception e) {
                            LOG.error("自动添加等级费率异常===========================" + e);
                        }
                    }
                }
            } else {
                if (Integer.parseInt(user.getGrade()) != 0) {
                    List<BrandRate> brandRates = brandMangeBusiness.findRateByBrand(user.getBrandId());
                    if (brandRates != null) {
                        for (BrandRate brandRate : brandRates) {
                            /* 自动添加等级费率 */
                            try {
                                Object map = addChannelGradeRateA(resMap, user, brandRate);
                            } catch (Exception e) {
                                LOG.error("自动添加等级费率异常===========================" + e);
                            }
                        }

                    }

                }
            }

            long userId = user.getId();
            long brandId = user.getBrandId();
            // 更新个人费率
            channelRateBusiness.queryByUserId(id, brandId, Long.parseLong(grade));

            user.setGrade(grade);
            Map<String, Object> map = new HashMap<>();
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESULT, userLoginRegisterBusiness.saveUser(user));
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            return map;
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    @Nullable
    private Map<String, Object> addChannelGradeRateA(Map<String, Object> resMap, User user, BrandRate brandRate) {
        BrandRate rateByBrandAndChannel = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), brandRate.getChannelId(), "0", PayType.TRADE.getValue());
        if(rateByBrandAndChannel!=null){
            if(brandRate.getRate().doubleValue()<rateByBrandAndChannel.getMinrate().doubleValue()){
                Map<String, Object> map = new HashMap();
                map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率小于该通道的最低费率"+rateByBrandAndChannel.getMinrate());
                return map;
            }
            if(brandRate.getRate().doubleValue()>rateByBrandAndChannel.getRate().doubleValue()){
                Map map = new HashMap();
                map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率大于该通道的普通会员的费率"+rateByBrandAndChannel.getRate());
                return map;
            }
        }else{
            Map map = new HashMap();
            map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "添加失败,您的贴牌未设置初始费率");
            return map;

        }
        ChannelRate channelRate = null;
        channelRate = channelRateBusiness.findChannelRateByUserid(user.getId(), brandRate.getChannelId());
        if(channelRate == null){
            channelRate = new ChannelRate();
            channelRate.setPayType((short) 1);
        }

        channelRate.setChannelId(brandRate.getChannelId());
        channelRate.setCreateTime(new Date());
        channelRate.setExtraFee(brandRate.getExtraFee());
        channelRate.setRate(brandRate.getRate());
        channelRate.setGradeRate(brandRate.getGradeRate());
        channelRate.setBrandId(user.getBrandId());
        channelRate.setUserId(user.getId());
        channelRate.setChannelMerType(brandRate.getChannelMerType());

        channelRate = channelRateBusiness.mergeChannelRate(channelRate);
        resMap.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
        resMap.put(CommonConstants.RESP_MESSAGE, "成功");
        resMap.put(CommonConstants.RESULT, channelRate);
        return resMap;
    }

    private Map<String, Object> addChannelGradeRate(Map<String, Object> resMap, User user, ThirdLevelRate thirdLevelRate) {
        BrandRate brandRate = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), thirdLevelRate.getChannelId(), "0", PayType.TRADE.getValue());
        if(brandRate!=null){
            if(thirdLevelRate.getRate().doubleValue()<brandRate.getMinrate().doubleValue()){
                resMap.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
                resMap.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率小于该通道的最低费率"+brandRate.getMinrate());
                return resMap;
            }
            if(thirdLevelRate.getRate().doubleValue()>brandRate.getRate().doubleValue()){
                resMap.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
                resMap.put(CommonConstants.RESP_MESSAGE, "添加失败,您的设置的费率大于该通道的普通会员的费率"+brandRate.getRate());
                return resMap;
            }

        }else{
            resMap.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
            resMap.put(CommonConstants.RESP_MESSAGE, "添加失败,您的贴牌未设置初始费率");
            return resMap;
        }

        ChannelRate channelRate = null;
        if(user.getId() != 0){
            channelRate = channelRateBusiness.findChannelRateByUserid(user.getId(), thirdLevelRate.getChannelId());
        }
        if(channelRate == null){
            channelRate = new ChannelRate();
        }

        channelRate.setChannelId(thirdLevelRate.getChannelId());
        channelRate.setCreateTime(new Date());
        channelRate.setExtraFee(brandRate.getExtraFee());
        channelRate.setRate(thirdLevelRate.getRate());
        channelRate.setGradeRate(brandRate.getGradeRate());
        channelRate.setBrandId(user.getBrandId());
        channelRate.setUserId(user.getId());
        channelRate.setChannelMerType(brandRate.getChannelMerType());

        channelRate = channelRateBusiness.mergeChannelRate(channelRate);
        resMap.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
        resMap.put(CommonConstants.RESP_MESSAGE, "成功");
        resMap.put(CommonConstants.RESULT, channelRate);
        return resMap;
    }

    // /** 根据brand_id修改等级 */
    // @SuppressWarnings("unused")
    // @RequestMapping(method = RequestMethod.POST, value =
    // "/v1.0/user/brand_id/grade/update")
    // public @ResponseBody Object updateUserInfoByBrand_idId(HttpServletRequest
    // request,
    // @RequestParam(value = "brand_id") long brandid, @RequestParam(value =
    // "grade") String grade) {
    // List<User> users = new ArrayList<User>();
    // users = userLoginRegisterBusiness.queryUserByGrade(brandid, grade);
    // for (User user : users) {
    // Brand brand = brandMangeBusiness.findBrandByManageid(user.getId());
    // if (brand != null) {
    // continue;
    // }
    // if (Integer.parseInt(grade) != 0) {
    // ThirdLevelDistribution distribution = thirdLevelBusiness
    // .getThirdLevelByBrandidandgrade(user.getBrandId(),
    // Integer.parseInt(grade));
    // if (distribution != null) {
    // List<ThirdLevelRate> thirdLevelRates = thirdLevelBusiness
    // .findAllThirdLevelRates(distribution.getId());
    // for (ThirdLevelRate thirdLevelRate : thirdLevelRates) {
    // /** 自动添加等级费率 */
    // URI uri = util.getServiceUrl("user", "error url request!");
    // String url = uri.toString() + "/v1.0/user/channel/grade/rate/add";
    // MultiValueMap<String, String> requestEntity = new
    // LinkedMultiValueMap<String, String>();
    // requestEntity.add("user_id", user.getId() + "");
    // requestEntity.add("brand_id", user.getBrandId() + "");
    // requestEntity.add("channel_id", thirdLevelRate.getChannelId() + "");
    // requestEntity.add("rate", thirdLevelRate.getRate() + "");
    // requestEntity.add("extra_fee", "0.000");
    // String result = restTemplate.postForObject(url, requestEntity,
    // String.class);
    // JSONObject jsonObject = JSONObject.fromObject(result);
    // }
    // }
    //
    // } else {
    // if (Integer.parseInt(user.getGrade()) != 0) {
    // List<BrandRate> brandRates = new ArrayList<BrandRate>();
    // brandRates = brandMangeBusiness.findRateByBrand(user.getBrandId());
    // if (brandRates != null) {
    // for (BrandRate brandRate : brandRates) {
    // /** 自动添加等级费率 */
    // URI uri = util.getServiceUrl("user", "error url request!");
    // String url = uri.toString() + "/v1.0/user/channel/rate/add";
    // MultiValueMap<String, String> requestEntity = new
    // LinkedMultiValueMap<String, String>();
    // requestEntity.add("user_id", user.getId() + "");
    // requestEntity.add("brand_id", user.getBrandId() + "");
    // requestEntity.add("channel_id", brandRate.getChannelId() + "");
    // requestEntity.add("rate", brandRate.getRate() + "");
    // requestEntity.add("extra_fee", "0.000");
    // String result = restTemplate.postForObject(url, requestEntity,
    // String.class);
    // JSONObject jsonObject = JSONObject.fromObject(result);
    // }
    //
    // }
    //
    // }
    // }
    // }
    // Map<String, Object> map = new HashMap<String, Object>();
    // map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
    // map.put(CommonConstants.RESP_MESSAGE, "成功");
    // return map;
    // }

    /**
     * 根据用户的token返回用户的基本信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/{token}")
    public @ResponseBody
    Object queryUserInfo(HttpServletRequest request, @PathVariable("token") String token) {

        Map<String, Object> map = new HashMap<>();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }
        User user = userLoginRegisterBusiness.queryUserById(userId);
        user.setUserToken(token);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;

    }

    /**
     * 验证登录密码
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/password/check")
    public @ResponseBody
    Object checkUserPass(HttpServletRequest request,
                         @RequestParam(value = "password") String password,
                         @RequestParam(value = "phone") String phone,
                         @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId) {
        HashMap<Object, Object> map = new HashMap<>();
        long brandId;
        Brand brand;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandManageBusiness.findBrandById(brandId);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                //根据手机号去查
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        if (user == null) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;

        }
        //判断数据库的密码和pass是否相等
        user = userLoginRegisterBusiness.queryUserByPhone(phone);
        String password1 = user.getPassword();
        if (password1 != null && Md5Util.getMD5(password).equals(password1)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESP_MESSAGE, "密码验证正确");
        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "密码验证失败");
        }

        return map;
    }

    /**
     * 修改登录密码 孙晓磊
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/password/updates")
    public @ResponseBody
    Object updateUserPassword(HttpServletRequest request,
                              @RequestParam(value = "phone") String phone,
                              @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                              @RequestParam(value = "password") String password) {
        HashMap<Object, Object> map = new HashMap<>();
        long brandId;
        Brand brand;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            brand = brandManageBusiness.findBrandById(brandId);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            } else {
                //根据手机号去查
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        if (user == null) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;

        }
        user.setPassword(Md5Util.getMD5(password));
        userLoginRegisterBusiness.saveUser(user);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;
    }


    /**
     * 登录后修改密码    type=3
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/password/updateAfterLogin")
    public @ResponseBody
    Object updateUserPassAfterLogin(HttpServletRequest request,
                                    @RequestParam(value = "phone", required = false) String phone,
                                    @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                                    @RequestParam(value = "vericode") String vericode, @RequestParam(value = "password") String password) {

        Map<String, Object> map = new HashMap<>();
        /* 如果短信验证码不为空， 那么需要 */
        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(phone);        //获取验证码场景类型
        /* 将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 3) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }

        long brandId;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
        }

        if (user == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;
        }
        user.setPassword(Md5Util.getMD5(password));
        userLoginRegisterBusiness.saveUser(user);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 忘记密码并更新用户登录密码    type=2
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/password/update")
    public @ResponseBody
    Object updateUserPass(HttpServletRequest request,
                          @RequestParam(value = "phone", required = false) String phone,
                          @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                          @RequestParam(value = "vericode") String vericode, @RequestParam(value = "password") String password) {

        Map<String, Object> map = new HashMap<>();
        /* 如果短信验证码不为空， 那么需要 */
        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(phone);        //获取验证码场景类型
        /* 将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 2) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }

        long brandId;
        Brand brand;
        User user;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
        }

        if (user == null) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;

        }

        user.setPassword(Md5Util.getMD5(password));
        userLoginRegisterBusiness.saveUser(user);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 更新用户的信息preuid
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/preuid/update")
    public @ResponseBody
    Object updateUserpreId(HttpServletRequest request,
                           @RequestParam(value = "id", required = false) long id,
                           // 昵称
                           @RequestParam(value = "nickName", required = false) String nickName,
                           // 全称
                           @RequestParam(value = "fullname", required = false) String fullname,
                           // 组织机构码
                           @RequestParam(value = "origcode", required = false) String origcode,
                           // 用户等级
                           @RequestParam(value = "grade", required = false) String grade,
                           // 上级Id
                           @RequestParam(value = "prephone", required = false) String prephone) {

        Map<String, Object> map = new HashMap<String, Object>();

        User user = userLoginRegisterBusiness.queryUserById(id);
        if (prephone != null && prephone.equals("")) {
            User preuser = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(prephone, user.getBrandId());

            if (preuser == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
                map.put(CommonConstants.RESP_MESSAGE, "preuid注册");
                return map;
            }
            List<User> users = new ArrayList<>();
            String phone = user.getPreUserPhone();
            int i = 0;
            if (phone != null) {
                for (int j = 0; j < 3; j++) {
                    user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, user.getBrandId());
                    if (user == null) {
                        break;
                    }
                    users.add(user);
                    if (user.getPreUserPhone() == null) {
                        break;
                    }
                    phone = user.getPreUserPhone();

                }

                for (User use : users) {

                    if (use.getId() == preuser.getId()) {
                        i++;
                    }
                }
            }
            if (i == 0) {

                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
                map.put(CommonConstants.RESP_MESSAGE, "不存在上下级关系");
                return map;
            }

            user.setPreUserId(preuser.getId());
            user.setPreUserPhone(preuser.getPhone());
            user.setInviteCode(preuser.getInviteCode());
        }
        // 昵称
        user.setNickName(nickName);
        // 全称
        user.setFullname(fullname);
        // 组织机构码
        user.setOrigcode(origcode);
        // 等级
        user.setGrade(grade);
        userLoginRegisterBusiness.saveUser(user);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 更新用户的支付密码    type=4
     */
    @Deprecated
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/paypass/update")
    public @ResponseBody
    Object updateUserPayPass(@RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "brandId", required = false, defaultValue = "-1") String sbrandId,
                             @RequestParam(value = "vericode") String vericode, @RequestParam(value = "paypass") String paypass) {

        Map<String, Object> map = new HashMap<>();
        /* 如果短信验证码不为空， 那么需要 */
        URI uri = util.getServiceUrl("notice", "error url request!");
        String url = uri.toString() + "/v1.0/notice/sms/vericode?phone=" + phone;
        String resultStr = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.fromObject(resultStr);
        String code = jsonObject.getString("result");
        int codetype = getSMSRecordType(phone);        //获取验证码场景类型
        /* 将错误情况区分开 付环宇2018.08.14*/
        if (StringUtils.isBlank(vericode)) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码不能为空");
            return map;
        }
        if (StringUtils.isBlank(code) || !code.equalsIgnoreCase(vericode) || codetype != 4) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
            map.put(CommonConstants.RESP_MESSAGE, "验证码错误");
            return map;
        }

        long brandId;
        User user;
        //Brand brand;
        try {
            brandId = Long.valueOf(sbrandId);
        } catch (NumberFormatException e) {
            brandId = -1;
        }
        if (brandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            //brand = brandManageBusiness.findBrandById(brandId);
            /*if ("6".equals(brand.getBrandType())) {*/
            user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandId);
            /*} else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }*/
        }

        if (user == null) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NO_REGISTER);
            map.put(CommonConstants.RESP_MESSAGE, "用户未注册");
            return map;

        }

        user.setPaypass(Md5Util.getMD5(paypass));
        userLoginRegisterBusiness.saveUser(user);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * Ios/安卓通过token返回用户信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/info/query/{token}")
    public @ResponseBody Object queryUserBytoken(@PathVariable("token") String token) {

        Map<String, Object> map = new HashMap<>();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;
        }
        User user = userLoginRegisterBusiness.queryUserById(userId);

        /* 获取身份证实名信息 */
        URI uri = util.getServiceUrl("paymentchannel", "error url request!");
        String url = uri.toString() + "/v1.0/paymentchannel/realname/userid";
        MultiValueMap<String, Long> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("userid", userId);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        JSONObject jsonObject = JSONObject.fromObject(result);
        JSONObject authObject = jsonObject.getJSONObject("realname");
        InfoUser infouser = new InfoUser();
        // 真实姓名

        String realname = authObject.containsKey("realname") ? authObject.getString("realname") : null;

        // 系统编号
        infouser.setUserid(user.getId());
        //信用卡管家激活状态
        infouser.setBankCardManagerStatus(user.getBankCardManagerStatus());
        // 用户手机号
        infouser.setPhone(user.getPhone());

        if (user.getRealnameStatus().equals("1")) {

            // 真是姓名
            infouser.setRealname(StringUtils.isBlank(realname) ? null : realname);
            // 身份证号
            String idcard = authObject.containsKey("idcard") ? authObject.getString("idcard") : null;
            infouser.setIdcard(StringUtils.isBlank(idcard) ? null : idcard);
        }
        // 用户性别
        infouser.setSex(user.getSex());

        // 实名状态
        infouser.setRealnameStatus(user.getRealnameStatus());

        // 商铺状态
        UserShops us = userShopsBusiness.findUserShopsByUid(userId);
        if (us != null) {
            infouser.setUsershopStatus(us.getStatus() != null ? us.getStatus() : "0");
        } else {
            infouser.setUsershopStatus("3");
        }

        // 级别
        infouser.setGrade(user.getGrade());
        // 提款费率
        BrandRate randRate = brandMangeBusiness.findRateByBrandAndChannel(user.getBrandId(), 1,user.getGrade(), PayType.WITHDRAW.getValue());
        if (randRate == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "没有设置通道id为" + user.getBrandId() + "的贴牌费率,请联系管理员设置相应费率才能正常使用!");
            return map;
        }
        infouser.setWithdrawFee(randRate.getExtraFee());
        // 注册时间
        infouser.setCreateTime(user.getCreateTime());
        infouser.setBrandId(user.getBrandId());

        Map<String, Object> role = userRoleResourceBusiness.queryUserRole(userId);
        long roleId = null == role.get("roleId") ? 5l : (long) role.get("roleId");
        infouser.setRoleId(roleId);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, infouser);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 后台过查询接口返回用户信息
     **/
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/info/query")
    public @ResponseBody
    Object queryUserByALL(@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
                          UserEntity entity) {    //entity 为条件查询用的实体类
        Pageable pageable = new PageRequest(entity.getPage(), entity.getSize(), new Sort(direction, entity.getSort()));
        Map<String, Object> map = new HashMap<>();
        /*获取登录者用户信息*/
        //User myuser = userLoginRegisterBusiness.queryUserById(myuserid);
        try {
            Date StartTimeDate = null;
            if (entity.getStart_time() != null && !"".equals(entity.getStart_time())) {
                StartTimeDate = DateUtil.getDateFromStr(entity.getStart_time());
            }
            Date endTimeDate = null;

            if (entity.getEnd_time() != null && !"".equals(entity.getEnd_time())) {
                endTimeDate = DateUtil.getDateFromStr(entity.getEnd_time());
            }
            if (entity.getPage() < 0) {
                entity.setPage(0);
            }

            if (entity.getUserId() != 0 || StringUtils.isNotBlank(entity.getPhone())) {
                List<User> users = new ArrayList<User>();
                if (StringUtils.isNotBlank(entity.getPhone())) {
                    if (entity.getBrandid() != -1) {
                        users.add(userLoginRegisterBusiness.queryUserByPhoneAndBrandid(entity.getPhone(), entity.getBrandid()));
                    } else {
                        users = userLoginRegisterBusiness.queryUsersByPhone(entity.getPhone());
                    }

                    if (users.size() == 0) {
                        map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                        map.put(CommonConstants.RESULT, null);
                        map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                        return map;
                    }
                } else {
                    users.add(userLoginRegisterBusiness.queryUserById(entity.getUserId()));
                }
                if (users.size() == 0) {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;

                }

                Map<String, Object> object = new HashMap<>();
                object.put("number", users.size());
                object.put("numberOfElements", users.size());
                object.put("totalElememts", users.size());
                object.put("totalpages", 1);
                object.put("content", getinfousers(users));
                map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
                map.put(CommonConstants.RESULT, object);
                map.put(CommonConstants.RESP_MESSAGE, "成功");
                return map;
            }

            Map<String, Object> userInfos;
            if (entity.getBrandid() == -1) {
                userInfos = userLoginRegisterBusiness.findInfoUserByall(entity.getFullname(), entity.getRealnameStatus(), entity.getShops_status(),
                        StartTimeDate, endTimeDate, pageable);
            } else {
                userInfos = userLoginRegisterBusiness.findInfoUserByall(entity.getBrandid(), entity.getFullname(), entity.getRealnameStatus(), entity.getShops_status(),
                        StartTimeDate, endTimeDate, pageable);
            }

            map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
            map.put(CommonConstants.RESULT, userInfos);
            map.put(CommonConstants.RESP_MESSAGE, "成功");
            return map;
        } catch (Exception ex) {
            LOG.error("UserLoginRegisterService.queryUserByALL(...) for `/v1.0/user/info/query`: ", ex);
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.查询失败了哦,请检查参数是否正确!!!");
            return map;
        }
    }

    /**
     * 查看贴牌下的未审核用户
     **/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/info/brand_id")
    public @ResponseBody
    Object seluserstatus(HttpServletRequest request,
                         // 品牌id
                         @RequestParam(value = "brand_id", defaultValue = "-1", required = false) String sbrandid,
                         // 品牌id
                         @RequestParam(value = "status", defaultValue = "0", required = false) String status) {
        Map<String, Object> map = new HashMap<>();
        if ("".equalsIgnoreCase(sbrandid.trim())) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.您的贴牌号有误,请检查后再重试!");
            return map;
        }
        long brandid;
        try {
            brandid = Long.valueOf(sbrandid.trim());
        } catch (NumberFormatException e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "亲.您的贴牌号有误,请检查后再重试!");
            return map;
        }

        if (brandid != -1) {
            map.put(CommonConstants.RESULT, userLoginRegisterBusiness.queryUserByStatus(brandid, status).size());
        } else {

            map.put(CommonConstants.RESULT, userLoginRegisterBusiness.queryUserByStatus(status).size());
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }


    /**
     * 获取用户的下级会员
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/info/{token}")
    public @ResponseBody
    Object afterUserInfou(HttpServletRequest request,
                          // token
                          @PathVariable("token") String token,
                          // 商户号
                          @RequestParam(value = "userId", defaultValue = "0", required = false) long userid,
                          // 手机号
                          @RequestParam(value = "phone", required = false) String phone,
                          // 身份证号
                          @RequestParam(value = "idcard", required = false) String idcard,
                          // 银行卡号
                          @RequestParam(value = "cardNo", required = false) String cardNo,
                          // 商户全称
                          @RequestParam(value = "fullname", required = false) String fullname,
                          // 起始时间
                          @RequestParam(value = "start_time", required = false) String startTime,
                          // 结束时间
                          @RequestParam(value = "end_time", required = false) String endTime,

                          // 等级
                          @RequestParam(value = "grade", required = false) String grade,

                          // 审核状态
                          @RequestParam(value = "realnameStatus", required = false) String realnameStatus,

                          @RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel,

                          @RequestParam(value = "page", defaultValue = "0", required = false) int page,
                          @RequestParam(value = "size", defaultValue = "20", required = false) int size,
                          @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
                          @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        Map<String, Object> map = new HashMap<>();

        long userId;
        long brandid;
        try {
            userId = TokenUtil.getUserId(token);
            brandid = TokenUtil.getBrandid(token);
        } catch (Exception e) {

            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_TOKEN);
            map.put(CommonConstants.RESP_MESSAGE, "token无效");
            return map;

        }
        Date StartTimeDate = null;
        if (startTime != null && !startTime.equalsIgnoreCase("")) {
            StartTimeDate = DateUtil.getDateFromStr(startTime);
        }
        Date endTimeDate = null;

        if (endTime != null && !endTime.isEmpty()) {
            try {
                endTimeDate = DateUtil.getDateFromStr(endTime);
            } catch (Exception e) {
                endTimeDate = null;
            }
        }

        List<User> users = new ArrayList<>();

        List<User> iusers;

        // List<InfoUser> infousers = new ArrayList<InfoUser>();

        String userIds = "" + userId;

        Long[] str2 = new Long[]{userId};

        for (int i = 1; lowerLevel == 0 ? (i > 0) : (i <= lowerLevel); i++) {
            iusers = userLoginRegisterBusiness.findInfoUsers(str2);
            userIds = "";
            if (iusers.size() == 0) {
                break;
            }
            for (User user : iusers) {
                users.add(user);
                userIds += user.getId() + ",";
            }
            if (userIds.length() > 0) {

                userIds = userIds.substring(0, userIds.length() - 1);
                String[] str1 = userIds.split(",");
                str2 = new Long[str1.length];
                for (int j = 0; j < str1.length; j++) {
                    str2[j] = Long.valueOf(str1[j]);
                }
            } else {
                break;
            }
        }

        if (phone != null && !phone.equals("")) {
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }
        }
        if (userid != 0) {
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userid);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }
        }
        /*
         * 身份证不为空判定
         **/
        if (idcard != null && !idcard.equals("")) {

            /* 获取身份证实名信息 */
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/realname/idcard";

            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
            requestEntity.add("idcard", idcard);

            String result = restTemplate.postForObject(url, requestEntity, String.class);
            if (result == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;
            }
            JSONObject jsonObject = JSONObject.fromObject(result);
            userId = Long.parseLong(jsonObject.get("userId").toString());
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userId);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }

        }
        if (cardNo != null && !cardNo.equals("")) {
            UserBankInfo ubi = userBankInfoBusiness.queryUserBankInfoByCardno(cardNo, "2");
            if (ubi == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "银行卡不存在");
                return map;
            } else {
                userId = ubi.getUserId();
            }
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userId);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }

        }
        if (phone == null && cardNo == null && idcard == null && userid == 0) {
            String ids = "";
            for (User user : users) {
                ids += user.getId() + ",";
            }
            if (ids.length() > 0) {
                userIds = ids.substring(0, ids.length() - 1);
                String[] str1 = ids.split(",");
                str2 = new Long[str1.length];
                for (int j = 0; j < str1.length; j++) {
                    str2[j] = Long.valueOf(str1[j]);
                }
                users = userLoginRegisterBusiness.findUserInfoByall(str2, fullname, realnameStatus, grade,
                        StartTimeDate, endTimeDate);
            }
        }
        String ids = "";
        Map<String, Object> object = new HashMap<>();
        int totalElememts = users.size();
        int totalpages = (totalElememts / size) + 1;
        object.put("number", page);
        if (page >= totalpages) {
            if (page > totalpages) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "页面超出");
                return map;
            }
        }
        object.put("numberOfElements", size);
        object.put("totalElememts", totalElememts);
        object.put("totalpages", totalpages);
        for (User user : users) {
            ids += user.getId() + ",";
        }
        if (ids.length() > 0) {
            userIds = ids.substring(0, ids.length() - 1);
            String[] str1 = ids.split(",");
            str2 = new Long[str1.length];
            for (int j = 0; j < str1.length; j++) {
                str2[j] = Long.valueOf(str1[j]);
            }
            users = userLoginRegisterBusiness.findInfoUsersPageable(str2, pageable);
        }
//		暂时开启贴牌商查询权限
//		Brand model = brandMangeBusiness.findByUserIdAndBrandId(userId,brandid);
//		if(model==null){
//			object.put("content", null);
//		}else{
//			object.put("content", getinfousers(users));
//		}
        object.put("content", getinfousers(users));
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;

    }

    /**
     * 获取用户的下级会员
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/{id}/info")
    public @ResponseBody
    Object afterUserInfouByuid(
            @PathVariable("id") long firstUid,
            // 商户号
            @RequestParam(value = "userId", defaultValue = "0", required = false) long userid,
            // 手机号
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "brand_id", defaultValue = "0", required = false) long brandid,
            // 身份证号
            @RequestParam(value = "idcard", required = false) String idcard,
            // 银行卡号
            @RequestParam(value = "cardNo", required = false) String cardNo,
            // 商户全称
            @RequestParam(value = "fullname", required = false) String fullname,
            // 起始时间
            @RequestParam(value = "start_time", required = false) String startTime,
            // 结束时间
            @RequestParam(value = "end_time", required = false) String endTime,
            // 等级
            @RequestParam(value = "grade", required = false) String grade,
            // 审核状态
            @RequestParam(value = "realnameStatus", required = false) String realnameStatus,
            @RequestParam(value = "lower_level", defaultValue = "0", required = false) int lowerLevel,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        Map<String, Object> map = new HashMap<>();

        long userId = firstUid;
        Date StartTimeDate = null;
        if (startTime != null && !startTime.equalsIgnoreCase("")) {
            StartTimeDate = DateUtil.getDateFromStr(startTime);
        }
        Date endTimeDate = null;

        if (endTime != null && !endTime.equalsIgnoreCase("")) {
            endTimeDate = DateUtil.getDateFromStr(endTime);
        }

        List<User> users = new ArrayList<User>();

        List<User> iusers;

        // List<InfoUser> infousers = new ArrayList<InfoUser>();

        String userIds = "" + userId;

        Long[] str2 = new Long[]{userId};

        for (int i = 1; lowerLevel == 0 ? (i > 0) : (i <= lowerLevel); i++) {
            iusers = userLoginRegisterBusiness.findInfoUsers(str2);
            userIds = "";
            if (iusers.size() == 0) {
                break;
            }
            for (User user : iusers) {
                users.add(user);
                userIds += user.getId() + ",";
            }
            if (userIds.length() > 0) {

                userIds = userIds.substring(0, userIds.length() - 1);
                String[] str1 = userIds.split(",");
                str2 = new Long[str1.length];
                for (int j = 0; j < str1.length; j++) {
                    str2[j] = Long.valueOf(str1[j]);
                }
            } else {
                break;
            }
        }

        if (phone != null && !phone.equals("")) {
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, brandid);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }
        }
        if (userid != 0) {
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userid);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }
        }
        /*
         * 身份证不为空判定
         **/
        if (idcard != null && !idcard.equals("")) {

            /*  获取身份证实名信息 */
            URI uri = util.getServiceUrl("paymentchannel", "error url request!");
            String url = uri.toString() + "/v1.0/paymentchannel/realname/idcard";

            MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
            requestEntity.add("idcard", idcard);

            String result = restTemplate.postForObject(url, requestEntity, String.class);
            if (result == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;
            }
            JSONObject jsonObject = JSONObject.fromObject(result);
            userId = Long.parseLong(jsonObject.get("userId").toString());
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userId);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }

        }
        if (cardNo != null && !cardNo.equals("")) {
            UserBankInfo ubi = userBankInfoBusiness.queryUserBankInfoByCardno(cardNo, "2");
            if (ubi == null) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "银行卡不存在");
                return map;
            } else {
                userId = ubi.getUserId();
            }
            String upz = "n";
            User userphone = userLoginRegisterBusiness.queryUserById(userId);
            if (userphone != null) {
                for (User user : users) {
                    if (user.getId() == userphone.getId()) {
                        upz = "y";
                        break;
                    }
                }
                if (upz.equals("y")) {
                    users.clear();
                    users.add(userphone);
                } else {
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                    map.put(CommonConstants.RESULT, null);
                    map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                    return map;
                }
            } else {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
                return map;

            }

        }
        if (phone == null && cardNo == null && idcard == null && userid == 0) {
            String ids = "";
            for (User user : users) {
                ids += user.getId() + ",";
            }
            if (ids.length() > 0) {
                userIds = ids.substring(0, ids.length() - 1);
                String[] str1 = ids.split(",");
                str2 = new Long[str1.length];
                for (int j = 0; j < str1.length; j++) {
                    str2[j] = Long.valueOf(str1[j]);
                }
                users = userLoginRegisterBusiness.findUserInfoByall(str2, fullname, realnameStatus, grade,
                        StartTimeDate, endTimeDate);
            }
        }
        Map<String, Object> object = new HashMap<>();
        int totalElememts = users.size();
        int totalpages = (totalElememts / size) + 1;
        object.put("number", page);
        if (page >= totalpages) {
            if (page > totalpages) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_VERI_CODE);
                map.put(CommonConstants.RESULT, null);
                map.put(CommonConstants.RESP_MESSAGE, "暂无数据");
                return map;
            }
        }
        object.put("numberOfElements", size);
        object.put("totalElememts", totalElememts);
        object.put("totalpages", totalpages);
        StringBuilder sb = new StringBuilder();
        for (User user : users) {
            sb.append(user.getId()).append(",");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
            String[] str1 = sb.toString().split(",");
            str2 = new Long[str1.length];
            for (int j = 0; j < str1.length; j++) {
                str2[j] = Long.valueOf(str1[j]);
            }
            users = userLoginRegisterBusiness.findInfoUsersPageable(str2, pageable);
        }

        object.put("content", getinfousers(users));
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        return map;

    }

    /**
     * 添加修改备注
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/update/remarks")
    public @ResponseBody
    Object updateUserremarksByid(
            @RequestParam(value = "userId") long userId, @RequestParam(value = "remarks") String remarks) {

        Map<String, Object> map = new HashMap<>();

        User user;

        user = userLoginRegisterBusiness.queryUserById(userId);

        if (user == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
            map.put(CommonConstants.RESULT, null);
            map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
            return map;
        }
        user.setRemarks(remarks);

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, userLoginRegisterBusiness.saveUser(user));
        map.put(CommonConstants.RESP_MESSAGE, "成功");

        /*
         * 推送信息
         **/

        return map;
    }

    /**
     * 添加修改账户归属
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/update/brand")
    public @ResponseBody
    Object updateUserbrandByid(
            @RequestParam(value = "oriBrandId", required = false, defaultValue = "-1") String soriBrandId,
            @RequestParam(value = "phone") String phone,
            @RequestParam(value = "brand_id") long brandId) {

        Map<String, Object> map = new HashMap<>(3);

        User user;
        long oriBrandId;
        try {
            oriBrandId = Long.valueOf(soriBrandId);
        } catch (NumberFormatException e) {
            oriBrandId = -1;
        }

        if (oriBrandId == -1) {
            user = userLoginRegisterBusiness.queryUserByPhone(phone);
        } else {
            Brand brand = brandManageBusiness.findBrandById(oriBrandId);
            if ("6".equals(brand.getBrandType())) {
                user = userLoginRegisterBusiness.queryUserByPhoneAndBrandid(phone, oriBrandId);
            } else {
                user = userLoginRegisterBusiness.queryUserByPhone(phone);
            }
        }

        Brand brand = brandMangeBusiness.findBrandById(brandId);

        if (user == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
            map.put(CommonConstants.RESULT, null);
            map.put(CommonConstants.RESP_MESSAGE, "用户不存在");
            return map;
        }
        if (brand == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_USER_NOT_EXISTED);
            map.put(CommonConstants.RESP_MESSAGE, "贴牌不存在");
            return map;
        }
        user.setBrandId(brand.getId());
        user.setBrandname(brand.getName());
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, userLoginRegisterBusiness.saveUser(user));
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 减去抽奖次数
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/update/encourageNum")
    public @ResponseBody
    Object updateUserbrandByid(@RequestParam(value = "user_id") long userid) {

        Map<String, Object> map = new HashMap<>();
        User user;
        try {
            user = userLoginRegisterBusiness.queryUserById(userid);
            if (user.getEncourageNum() == 0 || user.getEncourageNum() < 0) {
                map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
                map.put(CommonConstants.RESP_MESSAGE, "次数已用尽");
                return map;
            }
            user.setEncourageNum(user.getEncourageNum() - 1);
            userLoginRegisterBusiness.saveUser(user);
            return CommonsUtil.returnSuccess("");
        } catch (Exception e) {
            LOG.error("UserLoginRegisterService.updateUserbrandByid, 减去抽奖次数异常=====" + e);
            return CommonsUtil.returnError("减去抽奖次数失败！");
        }
    }

    // 根据省市县模糊查询用户信息
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/find/querybyprovince")
    public @ResponseBody
    Object queryUserByProvince(
            @RequestParam(value = "province", required = false) String province,
            @RequestParam(value = "city", required = false) String city,
            @RequestParam(value = "county", required = false) String county,
            @RequestParam(value = "page", defaultValue = "0", required = false) int page,
            @RequestParam(value = "size", defaultValue = "20", required = false) int size,
            @RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
            @RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {

        Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

        List<User> queryUserByProvince = userLoginRegisterBusiness.queryUserByProvince(province, city, county,
                pageable);

        List<InfoUser> list = getinfousers(queryUserByProvince);

        Map<String, Object> object = new HashMap<>();
        object.put("currentPage", pageable.getPageNumber()); // 当前页
        object.put("pageNum", pageable.getPageSize()); // 每页显示条数
        object.put("totalElements", queryUserByProvince.size()); // 总条数
        object.put("totalPages", queryUserByProvince.size() / pageable.getPageSize()); // 总页数
        object.put("content", list);

        Map<String, Object> map = new HashMap<>();
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, object);
        map.put(CommonConstants.RESP_MESSAGE, "查询成功");
        return map;
    }

    /**
     * 查询用户信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/find/by/userid")
    public @ResponseBody
    Object findByUserId(@RequestParam(value = "userId") long userId) {
        Map<String, Object> map = new HashMap<>();
        User user;
        try {
            user = userLoginRegisterBusiness.queryUserById(userId);
        } catch (Exception e) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
            map.put(CommonConstants.RESP_MESSAGE, "操作数据库异常,参数可能有误");
            return map;
        }
        if (user == null) {
            map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
            map.put(CommonConstants.RESP_MESSAGE, "数据库中无该userId记录");
            return map;
        }
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, user);
        map.put(CommonConstants.RESP_MESSAGE, "查询成功");
        return map;
    }

    /**
     * 查询是否激活用户
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/active/bankmanager")
    public @ResponseBody
    Object activeBankCardManager(@RequestParam(value = "userId") long userId) {

        try {
            User model = userLoginRegisterBusiness.queryUserById(userId);
            if (model == null) {
                return CommonsUtil.returnError("查询不到该用户,无法激活!");
            }
            if (model.getBankCardManagerStatus() == 1) {
                return CommonsUtil.returnError("该用户已激活!无法重复激活!");
            }
            model.setBankCardManagerStatus(1);
            model = userLoginRegisterBusiness.saveUser(model);
            return CommonsUtil.returnSuccess(model);
        } catch (Exception ex) {
            LOG.error("activeBankCardManager(...) for `/v1.0/user/active/bankmanager`: ", ex);
            return CommonsUtil.returnError("激活用户错误,参数可能有误,无法激活!");
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/query/brand/count")
    public @ResponseBody
    Object queryBrandUserCount(@RequestParam(value = "brandId") long brandId) {
        try {
            int count = userLoginRegisterBusiness.queryBrandUserCount(brandId);
            if (count == 0 || count < 100) {
                count = 100;
            }
            return CommonsUtil.returnSuccess(count);
        } catch (Exception e) {
            LOG.error("UserLoginRegisterService.queryBrandUserCount, 查询贴牌下用户数量异常=" + e);
            return CommonsUtil.returnError("查询用户数量失败!");
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/unactive/bankmanager")
    public @ResponseBody
    Object cancelUserActive(@RequestParam(value = "userId") String userId) {
        try {
            User model = userLoginRegisterBusiness.queryUserById(Long.parseLong(userId));
            if (model == null) {
                return CommonsUtil.returnError("查询不到用户");
            }

            if (0 == model.getBankCardManagerStatus()) {
                return CommonsUtil.returnError("该用户还没有激活");
            }

            model.setBankCardManagerStatus(0);
            userLoginRegisterBusiness.saveUser(model);
            return CommonsUtil.returnSuccess(model);
        } catch (Exception e) {
            LOG.error("UserLoginRegisterService.cancelUserActive, 查询用户异常=" + e);
            return CommonsUtil.returnError("保存用户异常");
        }
    }

    /**
     * 查询用户信息
     *
     * @param userId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/unactive/findUserById")
    public @ResponseBody
    Object findUserById(@RequestParam(value = "userId") long userId) {
        return userLoginRegisterBusiness.findUserById(userId);
    }

    @PostMapping(value = "/v1.0/user/findUserIdByPhone")
    public @ResponseBody Object findUserIdByPhone(String phone, long brandId) {
        try {
            Map<String, Object> res = userLoginRegisterBusiness.findUserIdByPhone(phone, brandId);
            return CommonsUtil.returnSuccess(res, "查询成功！");
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    @ResponseBody
    @PostMapping(value = "/v1.0/user/findPhoneByUserId")
    public Object findPhoneByUserId(String userIds, @RequestParam(required = false, defaultValue = "407") long brandId) {
        try {
            Map<String, Object> map = userLoginRegisterBusiness.findPhoneByUserId(userIds, brandId);
            return CommonsUtil.returnSuccess(map, "查询成功！");
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }

    @ResponseBody
    @PostMapping(value = "/v1.0/user/app/findRoleId")
    public Object appFindRoleId(long userId, @RequestParam(required = false, defaultValue = "407") long brandId) {
        try {
            Map<String, Object> map = userLoginRegisterBusiness.appFindRoleId(userId, brandId);
            return CommonsUtil.returnSuccess(map, "查询成功！");
        } catch (ServiceException e) {
            e.printStackTrace();
            return CommonsUtil.returnError(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonsUtil.returnError("服务器异常，请稍后再试！");
        }
    }
}
